//
//  MTEmailShowViewController.m
//  YuchBox
//
//  Created by Ivan on 11-11-1.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "MTEmailShowViewController.h"
#import "YuchBoxAppDelegate.h"
#import "LayoutParam.h"
#import "Utility.h"

@interface UILabelFlex : UILabel

@end

@implementation UILabelFlex

static const float max_label_width  = 320.0f;
static const float max_label_height = 4000.0f;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.numberOfLines = 0;
    }
    
    return self;
}

- (void)setText:(NSString *)text
{
    // computing the size
    //text = @"TESTESTESTSETSETSETSETSETSETSETESTttasdfTESTESTESTSETSETSETSETSETSETSETESTttasdfTESTESTESTSETSETSETSETSETSETSETESTttasdf";
    CGSize size = [text sizeWithFont:self.font constrainedToSize:CGSizeMake(max_label_width, max_label_height) lineBreakMode:UILineBreakModeWordWrap];
    CGFloat height = size.height > self.frame.size.height ? size.height : self.frame.size.height;
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, height);
    [super setText:text];
}

@end

@implementation MTEmailShowViewController
@synthesize mailBodyScrollView = _mailBodyScrollView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _titleTotalHeight = 0;
        _currentBottomY   = 0;
        _isSameEmail      = YES;
        
        _currentEmail     = nil;
    }
    return self;
}

- (void)dealloc
{
    [_fromView release];
    [_subjectView release];
    [_sendTimeView release];
    [_toView release];
    [_attachmentView release];
    
    [_contentHtmlView release];
    [_mailBodyScrollView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

#define CONTENT_LABEL_TAG   100
- (void)initRowView:(UIView *)view title:(NSString *)title
{
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, view.frame.size.height)];
    titleLabel.text             = title;
    titleLabel.textColor        = [UIColor darkGrayColor];
    titleLabel.font             = [UIFont systemFontOfSize:14];
    titleLabel.textAlignment    = UITextAlignmentRight;
    [view addSubview:titleLabel];
    [titleLabel release];
    
    UILabelFlex *contentLabel   = [[UILabelFlex alloc] initWithFrame:CGRectMake(60, 0, 260, view.frame.size.height)];
    contentLabel.font           = [UIFont systemFontOfSize:14];
    contentLabel.textAlignment  = UITextAlignmentLeft;
    contentLabel.tag            = CONTENT_LABEL_TAG;
    [view addSubview:contentLabel];
    [contentLabel release];
}

- (void)setContentLabelText:(UIView *)view content:(NSString *)content
{
    UILabelFlex *contentLabel = (UILabelFlex *)[view viewWithTag:CONTENT_LABEL_TAG];
    contentLabel.text = content;
}

- (void)setContentLabelText:(UIView *)view content:(NSString *)content font:(UIFont *)font
{
    UILabelFlex *contentLabel = (UILabelFlex *)[view viewWithTag:CONTENT_LABEL_TAG];
    contentLabel.font = font;
    // the height will autosize
    contentLabel.text = content;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationItem setTitle:@"邮件"];
    // Do any additional setup after loading the view from its nib.
    NSLog(@"Email show load");
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
    [self setMailBodyScrollView:scrollView];
    [self.view addSubview:self.mailBodyScrollView];
    
    [self.mailBodyScrollView setBackgroundColor:[UIColor grayColor]];
	[self.mailBodyScrollView setCanCancelContentTouches:NO];
    [self.mailBodyScrollView setClipsToBounds:YES];
    self.mailBodyScrollView.indicatorStyle = UIScrollViewIndicatorStyleBlack;
//    [self.mailBodyScrollView setClipsToBounds:YES];	// default is NO, we want to restrict drawing within our scrollview
//	[self.mailBodyScrollView setIndicatorStyle:UIScrollViewIndicatorStyleBlack];
    
    [self.mailBodyScrollView setScrollEnabled:YES];
//	UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image0.jpg"]];
//	[self.mailBodyScrollView addSubview:imageView];
//	[self.mailBodyScrollView setContentSize:CGSizeMake(320, imageView.frame.size.height)];

#define LABLE_HIGHT 30
    
    // mail title
    _subjectView    = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, LABLE_HIGHT)];
    _fromView       = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, LABLE_HIGHT)];
    _sendTimeView   = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, LABLE_HIGHT)];
    _toView         = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, LABLE_HIGHT)];
    _attachmentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, LABLE_HIGHT)];
    
    [self initRowView:_subjectView      title:@"标   题: "];
    [self initRowView:_fromView         title:@"发件人: "];
    [self initRowView:_sendTimeView     title:@"时   间: "];
    [self initRowView:_toView           title:@"收件人: "];
    [self initRowView:_attachmentView   title:@"附   件: "];
    
    [self.mailBodyScrollView addSubview:_subjectView];
    [self.mailBodyScrollView addSubview:_fromView];
    [self.mailBodyScrollView addSubview:_sendTimeView];
    [self.mailBodyScrollView addSubview:_toView];
    [self.mailBodyScrollView addSubview:_attachmentView];
//    _titleTotalHeight = LABLE_HIGHT * 5; // [self.view sizeThatFits:CGSizeZero].height;
    
    // mail body
    // content
//    _contentView     = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)]; // autosize
//    UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
//    contentLabel.font = [UIFont systemFontOfSize:14];
//    contentLabel.numberOfLines = 0;
//    NSString *d = @"LargetestLargetestLargetestLargetestLargetestLargetestLargetestLargetestLargetestLargetestLargetestLargetestLargetestLargetestLargetestLargetestLargetest";
//    CGSize size = [d sizeWithFont:contentLabel.font constrainedToSize:CGSizeMake(320, 2000) lineBreakMode:UILineBreakModeWordWrap];
//    NSLog(@"width:%f height:%f", size.width, size.height);
//    _contentView.frame = CGRectMake(0, LABLE_HIGHT*5, size.width, size.height);
//    contentLabel.frame = CGRectMake(0, 0, size.width, size.height);
//    contentLabel.text = d;
//    [_contentView addSubview:contentLabel];
//    [self.mailBodyScrollView addSubview:_contentView];
    
    // content html
    _contentHtmlView = [[UIWebView alloc] initWithFrame:CGRectMake(0, (LABLE_HIGHT*7), DEVICE_WIDTH, 420 - _titleTotalHeight)];
    [_contentHtmlView setDelegate:self];
     _contentHtmlView.scalesPageToFit = YES;
   
    [self.mailBodyScrollView addSubview:_contentHtmlView];
    
    [scrollView release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
//    NSLog(@"Email show unload");
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)adjustViewOneHeight:(UIView *)view
{
    //current_origin_y = view.frame.origin.y;
    UIView *viewLabel = [view viewWithTag:CONTENT_LABEL_TAG];
    
    view.frame = CGRectMake(view.frame.origin.x,
                            _currentBottomY,
                            view.frame.size.width, 
                            viewLabel.frame.size.height);
    _currentBottomY += viewLabel.frame.size.height;   
}

- (void)adjustViewHeight
{
    _currentBottomY = 0;
    [self adjustViewOneHeight:_subjectView];
    [self adjustViewOneHeight:_fromView];
    [self adjustViewOneHeight:_sendTimeView];
    [self adjustViewOneHeight:_toView];
    [self adjustViewOneHeight:_attachmentView];
    
    _contentHtmlView.frame = CGRectMake(_contentHtmlView.frame.origin.x, 
                                        _currentBottomY, 
                                        _contentHtmlView.frame.size.width,
                                        _contentHtmlView.frame.size.height);
    
}

- (void)loadEmail:(Email *)email
{
    if (nil == _currentEmail || email.uid != _currentEmail.uid) {
        _currentEmail = email;
        _isSameEmail = NO;
        
        // reload the view
        // clean up
//        [self myDealloc];
    } else {
        _isSameEmail = YES;
    }
}

- (void)viewDidAppear:(BOOL)animated
{
//    NSLog(@"Email show did appear");
//    UIView *view = [YuchBoxAppDelegate shareAppDelegate].navigationCotrollernew.view;
//    [Utility hideView:view atTag:NAVIGATION_BAR_LEFTBUTTONITEAM_TAG isHidden:YES];
//    [Utility hideView:view atTag:NAVIGATION_BAR_TITLEITEAM_TAG isHidden:YES];  
//    [self setContentLabelText:_subjectView      content:_currentEmail.subject font:[UIFont boldSystemFontOfSize:14]];
//    [self setContentLabelText:_fromView         content:_currentEmail.fromString];
//    [self setContentLabelText:_sendTimeView     content:[NSString stringWithFormat:@"%l", _currentEmail.sendTimestamp]];
//    [self setContentLabelText:_toView           content:@""];
//    [self setContentLabelText:_attachmentView   content:@"2个（图片:TEST.text..）查看所有附件"];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (_isSameEmail) {
        return;
    }

    [self setContentLabelText:_subjectView      content:_currentEmail.subject font:[UIFont boldSystemFontOfSize:14]];
    [self setContentLabelText:_fromView         content:_currentEmail.fromString];
    [self setContentLabelText:_sendTimeView     content:[NSString stringWithFormat:@"%l", _currentEmail.sendTimestamp]];
    [self setContentLabelText:_toView           content:@""];
    [self setContentLabelText:_attachmentView   content:@"2个（图片:TEST.text, TEST.text2, TEST.text3）查看所有附件"];
    [self adjustViewHeight];
    //NSString *totalContent = [NSString stringWithFormat:@"%@<br/>%@", _currentEmail.content, _currentEmail.contentHtml];
    [_contentHtmlView loadHTMLString: _currentEmail.contentHtml baseURL:nil];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    // WARNING if set the scorll delegate, the zoom will unavilable in the really iphone4 but no simulator
//    UIScrollView *scrollView = [[webView subviews] objectAtIndex:0];
//    [scrollView setDelegate:self];
    

//    NSLog(@"width:%f, height:%f", size.width, size.height);
//    NSLog(@"max:%f  , min:%f", scrollView.maximumZoomScale, scrollView.minimumZoomScale);
//   
    if (webView == _contentHtmlView) {        
        CGSize size = [webView sizeThatFits:CGSizeZero];
        webView.frame = CGRectMake(webView.frame.origin.x,
                                   _currentBottomY,  
                                   DEVICE_WIDTH,
                                   size.height);
        UIScrollView *scrollView = [[webView subviews] objectAtIndex:0];
        scrollView.contentSize = CGSizeMake(size.width, size.height);
        
        CGFloat totalHeight = size.height + _titleTotalHeight + NAVIGATION_BAR_HEIGHT;
        totalHeight = totalHeight < DEVICE_HEIGHT ? DEVICE_HEIGHT : totalHeight;

        [self.mailBodyScrollView setContentSize:CGSizeMake(DEVICE_WIDTH, totalHeight)];
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
